<template>
  <i v-if="type === 'icon'" :class="star ? 'el-icon-star-on' : 'el-icon-star-off'" @click="onStarClick"></i>
  <el-button
    v-else
    :type="star ? 'danger' : 'default'"
    plain
    :icon="star ? 'el-icon-star-on' : 'el-icon-star-off'"
    :loading="requesting"
    @click="onStarClick"
  >
    {{ star ? '取消收藏' : '收藏' }}
  </el-button>
</template>
<script>
import request from '@/utils/request'

export default {
  props: {
    size: { type: String, default: '' }, // 大小
    type: { type: String, default: 'default' }, // 类型
    matrixId: { type: String, default: '' }, // 指标ID
  },
  data() {
    return {
      star: false,
      requesting: false,
    }
  },
  created() {
    this.loadStar()
  },
  methods: {
    onStarClick() {
      if (this.star) {
        this.requestUnstar()
      } else {
        this.requestStar()
      }
    },
    async requestUnstar() {
      this.requesting = true
      try {
        const { success } = await request({
          url: '/matrix/collect/delete',
          method: 'post',
          data: { matrixId: this.$route.params.id || this.matrixId },
        })
        if (success) {
          this.star = false
          this.$message.success('已取消收藏')
        } else {
          this.$message.error('取消收藏失败')
        }
      } catch (error) {
        console.log('loadStar error=', error)
        this.$message.error('取消收藏失败, 请稍后重试')
      }
      this.requesting = false
    },
    async requestStar() {
      this.requesting = true
      try {
        const { success } = await request({
          url: '/matrix/collect/save',
          method: 'post',
          data: { matrixId: this.$route.params.id || this.matrixId },
        })
        if (success) {
          this.star = true
          this.$message.success('已添加收藏')
        } else {
          this.$message.error('添加收藏失败')
        }
      } catch (error) {
        console.log('loadStar error=', error)
        this.$message.error('添加收藏失败, 请稍后重试')
      }
      this.requesting = false
    },
    async loadStar() {
      try {
        const { success, data } = await request({
          url: '/matrix/collect/get',
          method: 'get',
          params: { matrixId: this.$route.params.id || this.matrixId },
        })
        if (success && data && data.id) {
          this.star = true
        } else {
          this.star = false
        }
      } catch (error) {
        console.log('loadStar error=', error)
        this.star = false
      }
    },
  },
}
</script>
